package com.qp.basics.estivate.mysql;

import com.qp.basics.estivate.*;
import com.qp.basics.estivate.support.DriverConnectionProvider;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DatabaseCreatorMysql implements DatabaseCreator {

	@Override
	public void createDatabaseAndInitialize(DriverConnectionProvider cp,
											String databaseName, String sourceFilePath) {
		createDatabase(cp, databaseName);
		initializeDatabase(cp, databaseName, sourceFilePath);
	}

	@Override
	public void createDatabase(ConnectionProvider cp, String databasename) {
		Connection con = cp.getConnection();
		try {
			con.createStatement().execute("create database " + databasename);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void initializeDatabase(DriverConnectionProvider cp,
			String databaseName, String sourceFilePath) {
		// TODO Auto-generated method stub
		try {
			String username = cp.getUser();
			String password = cp.getPassword();

			StringBuffer sb = new StringBuffer("cmd.exe /C mysql -u");
			sb.append(username);

			if (password != null && !password.equalsIgnoreCase(""))
				sb.append(" -p").append(password);

			sb.append(" ").append(databaseName).append("<")
					.append(sourceFilePath);
			// Process proc =
			// java.lang.Runtime.getRuntime().exec("cmd.exe /C mysql -uroot test2<d:/erp.sql");
			Process proc = Runtime.getRuntime().exec(sb.toString());

			BufferedInputStream bis = new BufferedInputStream(
					proc.getErrorStream());
			InputStreamReader inputStreamReader = new InputStreamReader(bis,
					"GBK");
			BufferedReader br = new BufferedReader(inputStreamReader);

			String line = null;
			while ((line = br.readLine()) != null)
				System.out.println(line);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws ClassNotFoundException,
			SQLException, IOException {
		//换成想要精简的数据库名
		String dbName = "gxw_bridge";
		DriverConnectionProvider cp = new DriverConnectionProvider();
		cp.setDriver("com.mysql.jdbc.Driver");
		cp.setPassword("xinghezhandui@123");
		cp.setUser("root");
		cp.setUrl("jdbc:mysql://121.36.222.100:3306/" + dbName + "?serverTimezone=Asia/Shanghai&useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8");
		Database mysqlDB = BaseDatabase.getDatabaseByType("mysql");
		mysqlDB.setConnectionProvider(cp);
		mysqlDB.setDatabaseName(dbName);
		List<Database> availableDatabases = mysqlDB.getAvailableDatabases();
		List<String> oldTableNames = new ArrayList<>();
		for (Database db : availableDatabases) {
			//需要精简的数据库名
			if (db.getDatabaseName().equals(dbName)) {
				Table[] tables = db.getTables();
				for (Table table : tables) {
					oldTableNames.add(table.getTableName());
				}
			}
		}
		String path = System.getProperty("user.dir");
		List<File> filesList = getFilesList(new File(path), new ArrayList<>());
		List<String> tableNames = new ArrayList<>();
		Pattern p = Pattern.compile("\"(.*?)\"");
		for (File file : filesList) {
			if (file.getName().endsWith(".java")) {
				List<String> strs = Files.readAllLines(Paths.get(file.getPath()));
				for (String str : strs) {
					if (file.getName().contains("DatabaseCreatorMysql")) {
						continue;
					}
					if (str.trim().startsWith("@Table(name") || str.trim().startsWith("@JoinTable(name")) {
						Matcher m = p.matcher(str);
						if (m.find()) {
							tableNames.add(m.group().trim().replace("\"", ""));
						}
					}
				}
			}
		}
		System.out.println("数据库中的表:" + oldTableNames);
		//不符合规则的漏网之鱼，大桥项目的漏网之鱼communicate_client, sensor_analysis_config
		tableNames.add("sys_config");
		System.out.println("必需的表:" + tableNames);
		List<String> tempList = new ArrayList<>();
		//深拷贝。。。先这么写了
		for (String oldTableName : oldTableNames) {
			tempList.add(oldTableName);
		}
		tempList.removeAll(tableNames);
		System.out.println("数据库中需要删除的表:" + tempList);
		Scanner scanner = new Scanner(System.in);
		System.out.println("现在要开始删除嘛？y/n");
		if (scanner.hasNext()) {
			if (scanner.next().equalsIgnoreCase("y")) {
				for (String tableName : tempList) {
					try {
						mysqlDB.dropTable(tableName);
					} catch (Exception e) {
						System.err.println(tableName + " 删除失败，原因是：" + e.getMessage());
						continue;
					}
				}
			}
		}
		tempList.clear();
		for (String tableName : tableNames) {
			tempList.add(tableName);
		}
		tempList.removeAll(oldTableNames);
		System.out.println("数据库中缺少必需的表:" + tempList);
		// Class.forName("com.mysql.jdbc.Driver");
		// Connection conn =
		// DriverManager.getConnection("jdbc:mysql://localhost:3306/test2","root","");
		// Statement stmt = conn.createStatement();
		// stmt.executeUpdate("source  C:\\Users\\jiangkai\\Desktop\\erp.sql");
		// stmt.execute("source  C:\\Users\\jiangkai\\Desktop\\erp.sql");

		// String statement
		// ="cmd.exe mysql -uroot -p use test2;source C:/Users/jiangkai/Desktop/erp.sql";
		// String statement ="javac";
		// String[] statements={
		// "cmd.exe /C cmd /C mysqldump -u root -p erp>d:/test.sql",
		// "cmd /c mysql -u root",
		// "source C:/Users/jiangkai/Desktop/erp.sql",
		// "cmd.exe /C mysqldump -uroot erp>d:/test.sql"
		// };
		//
		// Process proc =
		// java.lang.Runtime.getRuntime().exec("cmd.exe /C mysql -uroot test2<d:/erp.sql");
		// System.out.println("gogogo");
		// InputStream stderr=proc.getErrorStream();
		// BufferedReader br = new BufferedReader(new
		// InputStreamReader(stderr));

		// new String(line.getBytes(),"gb2312")

		// String mysql="mysqladmin -uroot -proot create databasename";
		// String mysql="mysqladmin -uroot -proot use test2";
		// java.lang.Runtime.getRuntime().exec("cmd /c "+mysql);
		// String path="mysql test2 < C:/Users/jiangkai/Desktop/erp.sql";
		// java.lang.Runtime.getRuntime().exec("cmd /c "+path);
	}

	public static List<File> getFilesList(File file, List<File> temp) {
		File[] listFiles = file.listFiles();
		for (File file2 : listFiles) {
			if (file2.isDirectory()) {
				getFilesList(file2, temp);
			} else {
				// if(file2.getAbsolutePath().contains(".java")){
				temp.add(file2);
				// }

			}
		}
		return temp;
	}

}
